from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse,Http404
import time
import uuid
import os.path
import json
import logging
# Create your views here.

def upload(request):
    if request.method == 'POST':
        callback = request.GET.get('CKEditorFuncNum')
        try:
            path = r"static/uploads/ckeditor/" + time.strftime("%Y%m%d",time.localtime()) + r"/"#还有这里，这里path修改你要上传的路径，我记得我是修改了的，这样就上传到了upload文件夹
            if not os.path.exists(path):
                os.makedirs(path)
            f = request.FILES["upload"]
            ext = os.path.splitext(f.name)[1]
            file_name = path + str(uuid.uuid4()) + ext
            des_origin_f = open(file_name, "wb+")
            for chunk in f:                 # 我修改的是这里，因为python后期的版本放弃了chunk函数，直接遍历类文件类型就可以生成迭代器了。
                des_origin_f.write(chunk)
            des_origin_f.close()
        except Exception as e:
            print(e)
        res = r"<script>window.parent.CKEDITOR.tools.callFunction(" + callback + ",'/" + file_name + "', '');</script>"
        return HttpResponse(res)
    else:
        raise Http404()

@csrf_exempt
def commonUpload(request):
    if request.method == 'POST':
        try:
            path = r"static/uploads/" + time.strftime("%Y%m%d", time.localtime()) + r"/"
            if not os.path.exists(path):
                os.makedirs(path)
            f = request.FILES["file"]
            ext = os.path.splitext(f.name)[1]
            file_name = path + str(uuid.uuid4()) + ext
            des_origin_f = open(file_name, "wb+")
            for chunk in f:                 # 我修改的是这里，因为python后期的版本放弃了chunk函数，直接遍历类文件类型就可以生成迭代器了。
                des_origin_f.write(chunk)
            des_origin_f.close()
        except Exception as e:
            logger = logging.getLogger('django')
            logger.error(e)
        res = {'code':0,'url':r'/'+file_name}
        return HttpResponse(json.dumps(res),content_type='application/json')